package com.zhengtoon.mctoon.conv.utils;

import com.alibaba.fastjson.JSON;
import com.qitoon.framework.core.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by liuzhenhua on 2016/12/13.
 */
public class ToonUtils {

    private static final Logger log = Logger.getLogger(ToonUtils.class);

    private final static String APPSECRET = SysConfig.getPropertyValue("config.appSecret");

    private final static String APPID = SysConfig.getPropertyValue("config.appId");
    private final static String APPTYPE = "app";
    private final static String SIGNTYPE = "md5";

    private final static String TOONMETHOD = "/open/getUserById";
    private final static String ROUTEURL = SysConfig.getPropertyValue("config.route_url");
    private final static String TOON_DOMAIN = "new.user.systoon.com";    // toon 域名地址

    /**
     * 通过toon userId 获取用户的手机号
     *
     * @param userId
     * @return
     */
    public static String getMobileByUserId(String userId) throws Exception {

        // 要返回的手机号
        String mobile = "";

        String authAppId = APPID;
        String authAppType = APPTYPE;
        String authSignType = SIGNTYPE;
        String authSign = "";

        // 参数
        String seq = "authAppId" + authAppId + "authAppType" + authAppType + "authSignType" + authSignType + "userId" + userId;
        // 签名
        authSign = sign(seq, APPSECRET, "UTF-8");
        // 参数
        String params = "?userId=" + userId + "&authAppId=" + authAppId + "&authAppType=" + authAppType
                + "&authSignType=" + authSignType + "&authSign=" + authSign;

        String url = "";
        String toonUrl = SysConfig.getPropertyValue("config.toonDomain");
        if (StringUtils.isNotBlank(toonUrl)) {
            url = toonUrl;
        } else {
            url = getToonApiRoute(ROUTEURL, TOON_DOMAIN);
        }

        // 发送http
        String result = HttpUtil.doGet(url + TOONMETHOD + params);
        // 处理返回参数
        Map<String, Object> ro = JSON.parseObject(result, HashMap.class);

        if (ro != null) {
            Map metaMap = JSON.parseObject(ro.get("meta").toString(), HashMap.class);
            if (metaMap != null && metaMap.get("code") != null && !"0".equals(metaMap.get("code").toString())) {
                throw new BusinessException("", "获取手机号失败");
            }
            Map<String, Object> resultMap = new HashedMap();
            resultMap = JSON.parseObject(ro.get("data").toString(), HashMap.class);
            if (resultMap != null && resultMap.get("mobilePhone") != null) {
                mobile = resultMap.get("mobilePhone").toString();
            }
        }
        return mobile;

    }

    private static String sign(String text, String key, String input_charset) {
        text = key + text + key;
        System.out.println("content==>" + text);
        return DigestUtils.md5Hex(getContentBytes(text, input_charset)).toUpperCase();
    }

    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 获取toon路由地址
     *
     * @param domain
     * @return
     */
    private static String getToonApiRoute(String routeUrl, String domain) {
        LinkedHashMap<String, String> m = new LinkedHashMap<>();
        m.put("domain", domain);
        try {
            String route = HttpXmlClient.httpGet(routeUrl, m);
            Map ro = JSON.parseObject(route, HashMap.class);
            String r = ro.get("data").toString();
            if (r.startsWith("http")) {
                return r;
            } else {
                return "http://" + r;
            }
        } catch (Exception e) {
            throw new BusinessException("", "获取路由失败", e);
        }
    }

    public static void main(String[] args) throws Exception {
       /* String str  = sign("authAppId85authAppTypeappauthSignTypemd5userId301212", APPSECRET,"UTF-8") ;
        System.out.println(str) ;*/
        System.out.println(getMobileByUserId("301212"));

    }

}
